package my.syncfilter;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class ZipUtil {
    private static Logger logger = LoggerFactory.getLogger(ZipUtil.class);


    public static void main(String[] args) throws Exception {
        FileOutputStream fou = new FileOutputStream("C:\\Users\\migu\\Desktop\\新建文件夹\\test.zip");
        List<String> ls= new ArrayList<>();
        ls.add("BaseTransfer.java");
        ls.add("DataTransfer.java");
        ls.add("DataTransferFactory.java");
        generateZip(fou,"C:\\Users\\migu\\Desktop\\新建文件夹",ls);
        fou.close();
    }

    public static void generateZip(ZipArchiveOutputStream zip, String basePath, String fileName) throws Exception {
        FileInputStream in = null;
        try {
            File file = new File(basePath + fileName);
            if (!file.exists()) {
                logger.info("{}:不存在文件{}", fileName);
                return;
            }
            ZipArchiveEntry zipEntry = new ZipArchiveEntry(file, fileName);
            zip.putArchiveEntry(zipEntry);
            try {
                in = new FileInputStream(file);
                byte[] buf = new byte[1024 * 1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    zip.write(buf, 0, len);
                }
            } finally {
                zip.closeArchiveEntry();
                zip.flush();
                if (in != null)
                    in.close();
            }
        } catch (Exception e) {
            logger.info("{}:压缩出现异常", fileName, e);
        }
    }

    public static void generateZip(OutputStream fou, String basePath, List<String> names) throws Exception {
        if (names == null || names.isEmpty()) return;
        ZipArchiveOutputStream archOuts = null;
        try {
            archOuts = new ZipArchiveOutputStream(fou);
            //archOuts.setEncoding("GBK");
            for (String name : names) {
                generateZip(archOuts, basePath, name);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (archOuts != null) {
                archOuts.finish();
                archOuts.close();
            }
        }
    }
}